package utils

import (
	"database/sql/driver"
	"fmt"
	"time"
)

// CustomTime 自定义时间类型，统一格式化为 YYYY-MM-DD HH:mm:ss
type CustomTime struct {
	time.Time
}

// TimeFormat 统一的时间格式
const TimeFormat = "2006-01-02 15:04:05"

// MarshalJSON 实现JSON序列化
func (ct CustomTime) MarshalJSON() ([]byte, error) {
	if ct.Time.IsZero() {
		return []byte("null"), nil
	}
	return []byte(fmt.Sprintf(`"%s"`, ct.Time.Format(TimeFormat))), nil
}

// UnmarshalJSON 实现JSON反序列化
func (ct *CustomTime) UnmarshalJSON(data []byte) error {
	if string(data) == "null" {
		ct.Time = time.Time{}
		return nil
	}
	
	// 移除引号
	str := string(data)
	if len(str) > 2 && str[0] == '"' && str[len(str)-1] == '"' {
		str = str[1 : len(str)-1]
	}
	
	parsedTime, err := time.Parse(TimeFormat, str)
	if err != nil {
		return err
	}
	
	ct.Time = parsedTime
	return nil
}

// Value 实现driver.Valuer接口，用于数据库存储
func (ct CustomTime) Value() (driver.Value, error) {
	if ct.Time.IsZero() {
		return nil, nil
	}
	return ct.Time, nil
}

// Scan 实现sql.Scanner接口，用于数据库读取
func (ct *CustomTime) Scan(value interface{}) error {
	if value == nil {
		ct.Time = time.Time{}
		return nil
	}
	
	switch v := value.(type) {
	case time.Time:
		ct.Time = v
	case *time.Time:
		if v != nil {
			ct.Time = *v
		}
	default:
		return fmt.Errorf("cannot scan %T into CustomTime", value)
	}
	
	return nil
}

// String 实现Stringer接口
func (ct CustomTime) String() string {
	if ct.Time.IsZero() {
		return ""
	}
	return ct.Time.Format(TimeFormat)
}

// NewCustomTime 创建新的CustomTime
func NewCustomTime(t time.Time) CustomTime {
	return CustomTime{Time: t}
}

// Now 获取当前时间的CustomTime
func Now() CustomTime {
	return CustomTime{Time: time.Now()}
}

// CustomTimePtr 自定义时间指针类型
type CustomTimePtr struct {
	*time.Time
}

// MarshalJSON 实现JSON序列化
func (ctp CustomTimePtr) MarshalJSON() ([]byte, error) {
	if ctp.Time == nil || ctp.Time.IsZero() {
		return []byte("null"), nil
	}
	return []byte(fmt.Sprintf(`"%s"`, ctp.Time.Format(TimeFormat))), nil
}

// UnmarshalJSON 实现JSON反序列化
func (ctp *CustomTimePtr) UnmarshalJSON(data []byte) error {
	if string(data) == "null" {
		ctp.Time = nil
		return nil
	}
	
	// 移除引号
	str := string(data)
	if len(str) > 2 && str[0] == '"' && str[len(str)-1] == '"' {
		str = str[1 : len(str)-1]
	}
	
	parsedTime, err := time.Parse(TimeFormat, str)
	if err != nil {
		return err
	}
	
	ctp.Time = &parsedTime
	return nil
}

// String 实现Stringer接口
func (ctp CustomTimePtr) String() string {
	if ctp.Time == nil || ctp.Time.IsZero() {
		return ""
	}
	return ctp.Time.Format(TimeFormat)
}

// NewCustomTimePtr 创建新的CustomTimePtr
func NewCustomTimePtr(t *time.Time) CustomTimePtr {
	return CustomTimePtr{Time: t}
}